package com.am.server.common.base.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import com.am.server.api.system.permission.service.SuperUserService;
import com.am.server.common.base.model.entity.BaseEntity;
import com.am.server.common.base.model.entity.EditableEntity;
import com.am.server.common.base.service.CommonService;
import com.am.server.common.config.SuperUser;
import com.am.server.config.sys.IdConfig;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author 阮雪峰
 */
@Service
public class CommonServiceImpl implements CommonService {

    private final SuperUserService superUserService;
    private final IdConfig idConfig;

    public CommonServiceImpl(SuperUserService superUserService, IdConfig idConfig) {
        this.superUserService = superUserService;
        this.idConfig = idConfig;
    }


    @Override
    public Long getLoginUserId() {
        return StpUtil.getLoginIdAsLong();
    }

    @Override
    public boolean isSupperUser() {
        SuperUser superUser = superUserService.get();
        return getLoginUserId().equals(superUser.getId());
    }

    @Override
    public void beforeSave(EditableEntity entity) {
        if (entity.getId() == null) {
            beforeSave((BaseEntity) entity);
            if (!isSupperUser()) {
                entity.setCreatedById(getLoginUserId());
            }
        }
        if (!isSupperUser()) {
            entity.setUpdatedById(getLoginUserId());
        }
    }

    @Override
    public void beforeSave(BaseEntity entity) {
        if (entity.getId() == null) {
            entity.setId(createNewId());
            entity.setCreatedTime(LocalDateTime.now());
        } else {
            entity.setUpdatedTime(LocalDateTime.now());
        }
    }

    @Override
    public Long createNewId() {
        return IdUtil.getSnowflake(idConfig.getWorkerId(), idConfig.getDataCenterId()).nextId();
    }
}
